<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>LayIM移动版测试</title>
    <link rel="stylesheet" href="${ctxPath}/static/xadmin/lib/layui/css/layui.mobile.css">
    <script src="${ctxPath}/static/xadmin/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="${ctxPath}/static/jquery/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="${ctxPath}/static/base/js/common.js"></script>
    <script type="text/javascript" src="${ctxPath}/static/base/js/c-im.js"></script>
</head>
<body>
<script>
    var page = 1;
    var name = '${name}';
    var userId = '${userId}';
    var initData = JSON.parse('${initData}');
    var ip = '${serviceIp}';
    var port = '${port}';
    var password = '';
    var username = '${userName}';
    var layer;
    layui.use('layer', function () {
        layer = layui.layer;
    });

    layui.use(['jquery', 'mobile', 'layer'], function () {
        var mobile = layui.mobile, layim = mobile.layim;
        var laytpl = layui.laytpl;
        var socket = createWebSocket('${ctxPath}', layim, userId, ip, port, username, password, layim);
        //基础配置
        layim.config({
            init: initData,
            isgroup: true,
            uploadImage: {url: '${ctxPath}/ajax/layim/uploadImg?number=' + username},
            uploadFile: {url: '${ctxPath}/ajax/layim/uploadFile?number=' + username},
            //可同时配置多个
            moreList: [{
                alias: 'find'
                , title: '发现'
                , iconUnicode: '&#xe628;' //图标字体的unicode，可不填
                , iconClass: '' //图标字体的class类名
            }, {
                alias: 'share'
                , title: '分享'
                , iconUnicode: '' //图标字体的unicode，可不填
                , iconClass: '' //图标字体的class类名
            }],
            //可同时配置多个
            tool: [
                {
                    alias: 'video', //工具别名
                    title: '发送网络视频', //工具名称
                    iconUnicode: '&#xe6ed;', //图标字体的unicode，可不填
                    iconClass: 'layui-icon-video' //图标字体的class类名
                },
                {
                    alias: 'chathistory', //工具别名
                    title: '聊天记录', //工具名称
                    iconUnicode: '&#xe60e;', //图标字体的unicode，可不填
                    iconClass: 'layui-icon-chat' //图标字体的class类名
                }
            ]
        });

        layim.on('tool(video)', function (insert, send, obj) { //事件中的tool为固定字符，而code则为过滤器，对应的是工具别名（alias）
            console.log("视频事件");
            layer.prompt({
                title: '发送网络视频'
                , formType: 4
                , shade: 0
            }, function (text, index) {
                layer.close(index);
                insert(text); //将内容插入到编辑器，主要由insert完成
                //send(); //自动发送
                console.log(this); //获取当前工具的DOM对象
                console.log(obj); //获得当前会话窗口的DOM对象、基础信息
            });
        });

        layim.on('tool(chathistory)', function (insert, send, obj) { //事件中的tool为固定字符，而code则为过滤器，对应的是工具别名（alias）
            console.info(obj.data)
            var data = obj.data;
            toChatHistroy(layim, data);
        });

        layim.on('sendMessage', function (data) {
            var To = data.to;
            var my = data.mine;
            var content = my.content;
            var msgType = 0;
            //当发送内容是图片是处理socekt内容

            if (content.indexOf("img[") != -1) {
                content = content.replace("img[", "");
                content = content.substring(0, content.length - 1);
                msgType = 1;
            }
            if (content.indexOf("file(") != -1) {
                content = content.replace("file(", "").replace(")[下载文件]", "");
                if (content.indexOf(".mp4") != -1) {
                    msgType = "2";
                    my.content = "video[" + content + "]";
                } else {
                    msgType = "3";
                }
            }
            var message = content + '%' + name;//TODO JIM群主说会扩展结果 暂时只能这样存
            var receiveId = To.id;

            console.log("发送内容" + JSON.stringify(message));

            if (!username) {
                return
            }

            if (!window.WebSocket) {
                //判断是发送好友消息还是群消息
                if (To.type == "friend") {//发送给朋友
                    var extras = {
                        'name': name
                    }
                    var addExtras = "name," + JSON.stringify(extras); //将JSON对象转化为JSON字符
                    var createTime = new Date().getTime();
                    var msg = "{\"from\": \"" + userId + "\",\"to\": \"" + receiveId + "\",\"cmd\":11,\"createTime\":" + createTime + ",\"chatType\":\"2\",\"msgType\": \"" + msgType + "\",\"content\": \"" + message + "\",\"extras\": \"" + addExtras + "\"}";
                    socket.send(msg);
                } else {//发送群组
                    var extras = {
                        name: To.groupname
                    }
                    var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + receiveId + "\",\"chatType\":\"1\",\"msgType\":\"" + msgType + "\",\"content\": \"" + message + "\"}";
                    socket.send(msg);
                }
                return;
            } else {
                if (socket.readyState == WebSocket.OPEN) {
                    //判断是发送好友消息还是群消息
                    if (To.type == "friend") {
                        var extras = name;
                        var addExtras = "name," + JSON.stringify(extras); //将JSON对象转化为JSON字符
                        var createTime = new Date().getTime();

                        var msg = "{\"from\": \"" + userId + "\",\"to\": \"" + receiveId + "\",\"cmd\":11,\"createTime\":" + createTime + ",\"chatType\":\"2\",\"msgType\": \"" + msgType + "\",\"content\": \"" + message + "\",\"name\": \"" + name + "\"}";
                        socket.send(msg);
                    } else {
                        var extras = {
                            name: To.groupname
                        }
                        var createTime = new Date().getTime();
                        var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + receiveId + "\",\"chatType\":\"1\",\"msgType\":\"" + msgType + "\",\"content\": \"" + message + "\"}";
                        socket.send(msg);
                    }
                }
            }

        });
        //监听查看更多记录
        layim.on('chatlog', function (data, ul) {
            toChatHistroy(layim, data);
        });
        layim.showNew('Friend', false); //标注“新的朋友”新动态
    });

    function showMoreChat(fromId, toId, type, rows) {
        loadChat(fromId, toId, type, rows);
    }

    function loadChat(fromId, toId, type, rows) {
        layui.use(['mobile'], function () {
            var mobile = layui.mobile, layim = mobile.layim;
            var url = "${ctxPath}/ajax/layim/historyMessage";
            var param = {
                id: toId,
                from_id: fromId,
                type: type,
                page: page,
                rows: rows,
                mobile: '1'
            };
            console.info(param);
            $.cajax(url, param, function (r) {
                var code = r.code;
                if (code == '1') {
                    var datas = r.data;
                    var totalPages = r.totalPages;
                    if (page == totalPages + 1) {
                        $.alert('没有更多记录');
                        return;
                    } else {
                        for (var d in datas) {
                            var data = datas[d];
                            var layimChatSystemLi = $('<li class="layim-chat-system"><span>' + data.createTimeStr + '</span></li>');
                            var layimChatLi;
                            if (data.createUserId == data.landUserId) {
                                layimChatLi = $('<li class="layim-chat-li layim-chat-mine">');
                            } else {
                                layimChatLi = $('<li class="layim-chat-li">');
                            }
                            var layimChatUser = $('<div class="layim-chat-user"><img src="' + data.avatar + '"><cite>' + data.createUserName + '</cite></div>');
                            var layimChatText;

                            data.content = layim.content(data.content);

                            if (data.msg_type == '0') {
                                layimChatText = $('<div class="layim-chat-text">' + data.content + '</div>');
                            } else if (data.msg_type == '1') {
                                layimChatText = $('<div class="layim-chat-text"><img src="' + data.content + '" /></div>');
                            } else if (data.msg_type == '2') {
                                layimChatText = $('<div class="layim-chat-text"><video src="' + data.content + '" controls="controls"></video></div>');
                            }
                            layimChatLi.append(layimChatUser).append(layimChatText);
                            var chatDiv = $('#chat-div');
                            chatDiv.prepend(layimChatLi).prepend(layimChatSystemLi);
                        }
                        page++;
                    }
                } else {
                    $.alert('加载聊天记录失败');
                }
            }, false, true);
        });
    }


    function toChatHistroy(layim, data) {
        page = 1;
        var type = data.type;
        //接收人ID
        var id = data.id;
        console.log("聊天记录" + JSON.stringify(data)); //得到当前会话对象的基本信息
        console.log(page); //得到当前聊天列表所在的ul容器，比如可以借助他来实现往上插入更多记录

        var temphtml = '<div class="rlayui-unselect layim-content"><div class="layim-chat layim-chat-friend"><div class="layim-chat-main" style="height:98%"><ul >' +
            '<li class="layim-chat-system"><span onclick="showMoreChat(\'' + userId + '\', \'' + id + '\', \'' + type + '\', 10);">查看更多记录</span></li>' +
            '<div id="chat-div"></div></ul></div></div></div>';
        layim.panel({
            title: '与 ' + data.name + ' 的聊天记录',  //标题
            tpl: temphtml, //模版
        });
        showMoreChat(userId, id, type, 10);
    }
</script>
</body>
</html>